import 'package:flutter/material.dart';
import 'package:x3_base_core/x3_base_core.dart';
import 'package:x3_component_core/x3_component_core.dart';
import 'package:x3_form_core/models/base_advanced_filter_model.dart';
import 'package:x3_form_core/provider/base_advanced_filter_provider.dart';
import 'package:x3_form_core/filter_components/widget/advanced_filter_item_container.dart';

/// 选择后，得到的数据是{"startTime": ,"endTime":}
/// 如果需要修改子项目布局 可以通过 [model.otherParam] 的 [itemText] 参数来修改
/// [itemText] 类型是String Function(String text) 也就是(String) => String
/// 如果需要"开始时间"and"结束时间"必须同时选择，则可以通过 [model.otherParam] 的 [operateSituation] 参数来更改
/// [operateSituation] 类型为String,[all]必须全部选择,后续可以继续拓展
class AdvancedFilterChoiceDateRange extends StatefulWidget {
  final BaseAdvancedFilterModel model;

  const AdvancedFilterChoiceDateRange({Key key, @required this.model}) : super(key: key);

  @override
  _AdvancedFilterChoiceDateRangeState createState() => _AdvancedFilterChoiceDateRangeState();
}

class _AdvancedFilterChoiceDateRangeState extends State<AdvancedFilterChoiceDateRange> {
  /// 开始时间
  String startTime = '开始时间';

  /// 结束时间
  String endTime = '结束时间';

  /// 共享类
  BaseAdvancedFilterProvider get filterProvider => BaseAdvancedFilterProvider.of(context, listen: false);

  /// 操作情况
  String get operateSituation => getOperateSituation();

  /// 系统颜色
  Color get systemColor => Theme.of(context).primaryColor == Colors.white ? Color(0xFF333333) : Theme.of(context).primaryColor;

  @override
  void initState() {
    super.initState();
    // 初始化
    var data = filterProvider.getDataSource(widget.model);
    if (data != null) {
      String start = BaseUtils.getKeyData(data, "startTime");
      DateTime startTry = BaseTransformUtil.stringAsDateTime(date: start);
      if (start.isNotEmpty && startTry != null) {
        startTime = start;
      }
      String end = BaseUtils.getKeyData(data, "endTime");
      DateTime endTry = BaseTransformUtil.stringAsDateTime(date: end);
      if (end.isNotEmpty && endTry != null) {
        endTime = end;
      }
    }

    /// 重置监听
    filterProvider.resetStream.listen((e) {
      var data = filterProvider.getDataSource(widget.model);
      startTime = "开始时间";
      endTime = "结束时间";
      if (data != null) {
        String start = BaseUtils.getKeyData(data, "startTime");
        DateTime startTry = BaseTransformUtil.stringAsDateTime(date: start);
        if (start.isNotEmpty && startTry != null) {
          startTime = start;
        }
        String end = BaseUtils.getKeyData(data, "endTime");
        DateTime endTry = BaseTransformUtil.stringAsDateTime(date: end);
        if (end.isNotEmpty && endTry != null) {
          endTime = end;
        }
      }
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return AdvancedFilterItemContainer(
      isRequired: widget.model.required,
      title: widget.model.name,
      child: buildContent(),
    );
  }

  Widget buildContent() {
    return Row(
      children: [
        Expanded(child: buildItem(text: startTime, onTap: selectStartTimeEvent, type: 'start')),
        SizedBox(width: 12.0),
        Expanded(child: buildItem(text: endTime, onTap: selectEndTimeEvent, type: 'end')),
      ],
    );
  }

  Widget buildItem({@required String text, @required Function() onTap, @required String type}) {
    return InkWell(
      onTap: onTap,
      child: Container(
        width: double.infinity,
        height: 32,
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border.all(color: isOperateColor(text, type: type), width: 1),
          borderRadius: BorderRadius.circular(3),
        ),
        alignment: Alignment.center,
        child: Row(
          children: [
            SizedBox(width: 8),
            buildIcon(Colors.transparent),
            Expanded(child: Center(child: Text(getItemText(text)))),
            buildIcon(isOperateColor(text, type: type)),
            SizedBox(width: 8),
          ],
        ),
      ),
    );
  }

  Widget buildIcon(Color iconColor) {
    return Container(child: Icon(BaseIconData.x3Date, color: iconColor, size: 16));
  }

  String getItemText(String text) {
    if (widget.model.otherParam != null && widget.model.otherParam.containsKey("itemText")) {
      String itemText = widget.model.otherParam['itemText'](text);
      return itemText;
    }
    DateTime dateTime = DateTime.tryParse(text).toLocal();
    if (dateTime == null) return text;
    return "${dateTime.year}~${BaseTransformUtil.format(dateTime.month)}~${BaseTransformUtil.format(dateTime.day)}";
  }

  Color isOperateColor(String text, {@required String type}) {
    bool isOperate = text != "开始时间" && text != "结束时间";
    if (isOperate) return systemColor;
    if (operateSituation == "all") {
      DateTime start = BaseTransformUtil.stringAsDateTime(date: startTime);
      DateTime end = BaseTransformUtil.stringAsDateTime(date: endTime);
      if ((start != null && end == null) || (start == null && end != null)) {
        return Color(0xFFF04134);
      }
    }
    return Color(0xFFDFDFDF);
  }

  /// 选择开始时间
  void selectStartTimeEvent() {
    DateTime start = DateTime.tryParse(startTime);
    DateTime end = DateTime.tryParse(endTime);
    BaseComponentUtils.openDatePicker(context, currentDate: start, onDateChanged: (DateTime dateTime) {
      if (end != null && dateTime.isAfter(end)) {
        BaseUtils.showToast("开始时间不能大于结束时间");
        return;
      }
      startTime = BaseTransformUtil.dateTimeAsString(dateTime.toLocal());
      filterProvider.setDataSource(widget.model, getParam());
      setState(() {});
    });
  }

  /// 选择结束时间
  void selectEndTimeEvent() {
    DateTime start = DateTime.tryParse(startTime);
    DateTime end = DateTime.tryParse(endTime);
    BaseComponentUtils.openDatePicker(context, currentDate: end, onDateChanged: (DateTime dateTime) {
      if (start != null && dateTime.isBefore(start)) {
        BaseUtils.showToast("结束时间不能小于开始时间");
        return;
      }
      endTime = BaseTransformUtil.dateTimeAsString(dateTime.toLocal());
      filterProvider.setDataSource(widget.model, getParam());
      setState(() {});
    });
  }

  Map<String, dynamic> getParam() {
    DateTime startDateTime = DateTime.tryParse(startTime).toLocal();
    String start = startDateTime == null ? "" : "${BaseTransformUtil.dateTimeAsString(DateTime(startDateTime.year, startDateTime.month, startDateTime.day, 0, 0, 0, 0))}";
    DateTime endDateTime = DateTime.tryParse(endTime).toLocal();
    String end = endDateTime == null ? "" : "${BaseTransformUtil.dateTimeAsString(DateTime(endDateTime.year, endDateTime.month, endDateTime.day, 23, 59, 59, 999))}";
    return {"startTime": start, "endTime": end};
  }

  /// 获取操作情况
  String getOperateSituation() {
    if (!widget.model.otherParam.containsKey("operateSituation")) return '';
    return widget.model.otherParam["operateSituation"];
  }
}
